/**
 * @Author：ming
 * @Date：2023/10/29 10:08 PM
 * @Filename：Hot347
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

/**
 * @author ming
 */
public class Hot347 {
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i],map.getOrDefault(nums[i],0)+1 );
        }

        ArrayList<Integer> list = new ArrayList<>(map.keySet());
        Collections.sort(list, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return map.get(o2)-map.get(o1);
            }
        });

        int[] target = new int[k];
        for (int i = 0; i < k; i++) {
            target[i]=list.get(i);
        }
        return target;
    }
}
